package com.baselibrary.utils;

import android.content.Context;
import android.graphics.Rect;
import android.util.TypedValue;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;

/**
 * 首页瀑布流间距
 */
public class StaggeredItemDecoration extends RecyclerView.ItemDecoration {
    private Context context;
    private float interval;
    private boolean isHome;

    /**
     * @param interval item的间距
     */
    public StaggeredItemDecoration(Context context, float interval, boolean isHome) {
        this.context = context;
        this.interval = interval;
        this.isHome = isHome;
    }

    @Override
    public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, RecyclerView parent, @NonNull RecyclerView.State state) {
        int interval = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
                this.interval, context.getResources().getDisplayMetrics());
        if (isHome) {
            //true = 首页 -》banner不設置
            if (parent.getChildLayoutPosition(view) != 0) {
                setOutRect(outRect, view, interval);
            } else {
                outRect.bottom = interval / 2 + 10;
            }
        } else {
            setOutRect(outRect, view, interval);
        }
    }

    private void setOutRect(@NonNull Rect outRect, @NonNull View view, int interval) {
        StaggeredGridLayoutManager.LayoutParams params = (StaggeredGridLayoutManager.LayoutParams) view.getLayoutParams();
        // 获取item在span中的下标
        int spanIndex = params.getSpanIndex();
        if (spanIndex % 2 == 0) {
            outRect.right = interval / 2 + 1;
            outRect.left = interval + 3;
        } else {
            outRect.right = interval + 2;
            outRect.left = interval / 2 + 1;
        }
        // 下方间隔
        outRect.bottom = interval / 2 + 10;
    }
}
